package org.linlinjava.litemall.db.config;

import java.util.Properties;

import org.beetl.core.fun.ObjectUtil;
import org.beetl.sql.core.ClasspathLoader;
import org.beetl.sql.core.Interceptor;
import org.beetl.sql.core.NameConversion;
import org.beetl.sql.core.SQLManager;
import org.beetl.sql.core.db.DBStyle;
import org.beetl.sql.ext.DebugInterceptor;
import org.beetl.sql.ext.spring4.BeetlSqlDataSource;
import org.beetl.sql.ext.spring4.SqlManagerFactoryBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

import com.ibeetl.starter.BeetlSqlCustomize;
import com.ibeetl.starter.BeetlSqlProperties;

/**
 * 用于拓展公用方法
 * @author Administrator
 *
 * @param <T>
 */
@Component
public class BeetlSqlConfig  {
	
	@Bean(name = "sqlManagerFactoryBean")
	public SqlManagerFactoryBean getSqlManagerFactoryBean(BeetlSqlDataSource source  , BeetlSqlCustomize  cust  ,Environment env ) throws Exception {
		
		ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
		if(classLoader==null) {
			classLoader = this.getClass().getClassLoader();
		}
		
		BeetlSqlProperties beetlSqlProperties = new BeetlSqlProperties(env);
		SqlManagerFactoryBean factory = new SqlManagerFactoryBean();
		
		factory.setCs(source);
		factory.setDbStyle((DBStyle) ObjectUtil.tryInstance(beetlSqlProperties.getDbStyle(),classLoader));
		factory.setInterceptors( env.getProperty("beetl-beetlsql.dev", Boolean.class, true)? new Interceptor[] { new DebugInterceptor() } : new Interceptor[0]);
		factory.setNc((NameConversion)ObjectUtil.tryInstance(beetlSqlProperties.getNameConversion(),classLoader));
		ClasspathLoader loader = new ClasspathLoader(beetlSqlProperties.getSqlPath());
		//不能直接设置通过loader的autocheck
		Properties ps = new Properties();
		ps.put("PRODUCT_MODE",  env.getProperty("beetl-beetlsql.dev", Boolean.class, true)?"false":"true");
		factory.setExtProperties(ps);
		factory.setSqlLoader(loader);
		
		if(cust!=null) {
			cust.customize(factory);
		}
		return factory;
	}
	
	
	
	@Bean
	public BeetlSqlCustomize beetlSqlCustomize(){
		return new BeetlSqlCustomize() {
			
			@Override
			public void customize(SqlManagerFactoryBean sqlManagerFactoryBean) {
				try {
					SQLManager sqlManager = (SQLManager)sqlManagerFactoryBean.getObject();
					
					sqlManager.setDefaultBeanProcessors(new ItexBeanProcessor(sqlManager));
					Interceptor[] inters = sqlManager.getInters();
					Interceptor[] new_inters = new Interceptor[inters.length+1];
					for (int i = 0; i < inters.length; i++) {
						new_inters[i] = inters[i];
					}
					new_inters[new_inters.length-1]  = new ItextInterceptor();
					sqlManager.setInters(new_inters);
					
				} catch (Exception e) {
					throw new RuntimeException(e);
				}
				
			}
		};
	}
	
}
